<template>
 <div class="loginContainer">
     <van-icon name="arrow-left" class="arrow-left" @click="$router.back()"/>
    <div class="loginInner">
      <div class="login_header">
        <div class="login_logo">仿饿了么</div>
        <div class="login_header_title">
          <a href="javascript:;" :class="{on:loginWay}" @click="loginWay=true">短信登录</a>
          <a href="javascript:;" :class="{on:!loginWay}" @click="loginWay=false">密码登录</a>
        </div>
      </div>
      <!-- 内容部分 -->
      <div class="login_content">
         <form @submit.prevent="login">
             <!-- 短信登录 -->
           <div :class="{on: loginWay}">
                 <section class="login_message">
                   <input type="tel" maxlength="11" placeholder="手机号" v-model="phone" />
                  <button :disabled="!rightPhone" class="get_verification" :class="{right_phone:rightPhone}" @click.prevent="getCode">{{computeTime>0 ? `(${computeTime}s)已发送` : '获取验证码'}}</button>
                 </section>
                 <section class="login_verification">
                     <input type="tel" maxlength="8" placeholder="验证码" v-model="code">
                 </section>
                 <section class="login_hint">
                     温馨提示：未注册饿了么帐号的手机号，登录时将自动注册，且代表已同意
                      <a href="javascript:;">《用户服务协议》</a>
                 </section>
            </div>
             <!-- 密码登录 -->
            <div :class="{on:!loginWay}">
                <section class="login_message">
                 <input type="tel" maxlength="11" placeholder="手机/邮箱/用户名" v-model="name" />
                </section>
                <section class="login_verification">
                  <input type="text" maxlength="8" placeholder="密码" v-if="showPwd" v-model="pwd"/>
                  <input type="password" maxlength="8" placeholder="密码" v-else v-model="pwd"/>
                  <section class="switch_button" :class="showPwd ? 'on' : 'off'" @click="showPwd = !showPwd">
                      <section class="switch_circle" :class="{right : showPwd}"></section>
                      <section class="switch_text">{{showPwd ? '' : ''}}</section>
                  </section>
                </section>

                <section class="login_message">
                      <input type="text" maxlength="11" placeholder="验证码" v-model="captcha">
                     <img class="get_verification" src="http://localhost:4000/captcha" alt="captcha" @click="getCaptcha" ref="captcha">
                </section>

            </div>
            <button class="login_submit">登录</button>
         </form>
      </div>
    </div>
    <div class="about">
      <a href="#">关于我们</a>
    </div>
    <AlertTip :alertText="alertText" v-show="alertShow" @closeTip="closeTip"/>
  </div>
</template>

<script>
import AlertTip from '../../components/AlertTip/AlertTip.vue'
import { reqSendCode, reqSmsLogin, reqPwdLogin } from '../../api'
export default {
  name: 'Login',
  data () {
    return {
      loginWay: false, // true代表短信登陆, false代表密码
      phone: '', // 手机号,
      computeTime: 0,
      code: '', // 验证码
      timer: null,
      showPwd: false,
      captcha: '',
      pwd: '',
      name: '',
      alertText: '', // 提示文本
      alertShow: false // 是否显示警告框
    }
  },
  computed: {
    rightPhone () {
      // 利用正则对手机号匹配
      return /^1[3456789]\d{9}$/.test(this.phone)
    }
  },
  methods: {
    async getCode () {
      if (!this.computeTime) {
        this.computeTime = 30
        this.timer = setInterval(() => {
          this.computeTime--
          if (this.computeTime <= 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        // 发送ajax请求(向指定手机号发送验证码短信)
        const result = await reqSendCode(this.phone)
        if (result.code === 1) { // 手机号验证失败
          // 显示提示
          this.showAlert(result.msg)
          // 停止计时
          if (this.computeTime) {
            this.computeTime = 0
            clearInterval(this.intervalId)
            this.intervalId = undefined
          }
        }
      }
      // 只要手机号填写正确 短信验证码也可以在服务端的控制台中查看
    },
    async login () {
      let result
      // 短信验证
      if (this.loginWay) {
        console.log(this.rightPhone)
        const { phone, code } = this
        if (!this.rightPhone) {
          this.showAlert('手机号不正确')
          return
        } else if (!/^\d{6}$/.test(this.code)) {
          this.showAlert('验证码必须是6位')
          return
        }
        // 发送ajax请求短信登录
        result = await reqSmsLogin(phone, code)
      } else {
        const { name, pwd, captcha } = this
        // 密码验证
        if (!/^[a-zA-Z0-9_-]{4,16}$/.test(this.name)) {
          this.showAlert('用户名需要4到16位（字母，数字，下划线，减号）')
          return
        } else if (!/^[a-zA-Z0-9_-]{4,16}$/.test(this.pwd)) {
          this.showAlert('请输入正确密码')
          return
        } else if (!this.captcha) {
          this.showAlert('图片验证码不正确')
          return
        }
        // 发送ajax请求密码登录
        result = await reqPwdLogin({ name, pwd, captcha })
      }
      // 停止计时
      if (this.computeTime) {
        this.computeTime = 0
        clearInterval(this.intervalId)
        this.intervalId = undefined
      }
      // 根据结果数据处理
      if (result.code === 0) {
        const user = result.data
        // 将user保存在vuex的state中
        this.$store.dispatch('recordUser', user)
        // 去个人中心页面
        this.$router.replace('/person')
      } else {
        // 重新获取验证码
        this.getCaptcha()
        const msg = result.msg
        // 显示错误信息
        this.showAlert(msg)
      }
    },
    // 获取一次性验证码
    getCaptcha () {
      // 每次指定的src值要不一样
      this.$refs.captcha.src = 'http://localhost:4000/captcha?time=' + Date.now()
    },
    showAlert (alertText) {
      this.alertShow = true
      this.alertText = alertText
    },
    // 关闭警告框
    closeTip () {
      this.alertShow = false
      this.alertText = ''
    }

  },
  components: {
    AlertTip: AlertTip
  }
}
</script>

<style lang="less" scoped>
.arrow-left{
    color: #aaa;
    position: absolute;
    left: 5px;
    top: 8px;
}
.loginContainer {
  width: 100%;
  height: 100%;
  background: #fff;
}
.loginInner {
  width: 80%;
  margin: 0 auto;
  padding-top: 60px;
}
.loginInner .login_header .login_logo {
  color: #1989fa;
  font-weight: bolder;
  font-size:40px;
  text-align:center;
}
.login_header .login_header_title{
  text-align:center;
  padding-top:40px;
}
.login_header_title a{
  text-decoration: none;
  font-size:14px;
  color:#333;
  padding-bottom:4px;
}
.login_header_title a:first-child{
  margin-right:40px;
}
.login_header_title a.on{
  color :#1989fa;
  font-weight: bolder;
  border-bottom:2px solid #1989fa;
}
.login_content form div{
   display:none;
}
.login_content form div.on{
  display:block;
}
.login_content form  input{
  width:100%;
  height:100%;
  border: 1px solid #ddd;
  border-radius :4px;
  outline: none;
  padding-left:10px;
  box-sizing: border-box;

}
.login_content form  input:focus{
   border: 1px solid #1989fa;
}
.login_message{
   position:relative;
   margin-top:16px;
   height:48px;
   font-size:14px;
   background:#fff;
}
.login_message .get_verification{
 position:absolute;
 top:50%;
 right:10px;
 transform: translateY(-50%);
 border:none;
 color:#ccc;
 background :transparent;
 font-size:14px;
}
.login_message .get_verification.right_phone{
 color:#000;
}
.login_hint{
  color:#999;
  margin-top:12px;
  font-size:14px;
  line-height:20px;
}
.login_hint a{
  text-decoration: none;
   color :#1989fa;
}

.login_verification{
  position:relative;
  margin-top:16px;
  height:48px;
  font-size:14px;
  background:#fff;
  .get_verification{
    position: absolute;
    right: 3px;
    top:50%;
    transform:translateY(-50%);
  }
}
.login_verification .switch_button{
  border:1px solid #ddd;
  width:30px;
  height:16px;
  position:absolute;
  top:50%;
  right:10px;
  transform: translateY(-50%);
  border-radius:8px;
  padding:0 6px;
  line-height:16px;
  font-size:12px;
  transition:  background-color 0.3s;
}
.login_verification .switch_button.on{
   background :#1989fa;
}
.login_verification .switch_button.off{
 background:#fff;
}
.switch_button .switch_circle{
    background:#fff;
    border:1px solid #ddd;
    border-radius:50%;
    width:16px;
    height:16px;
    position:absolute;
    left:-1px;
    top:-1px;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,0.1);
}
.switch_button .switch_circle.right{
  transform :translateX(30px);
}
.switch_button  .switch_text{
   color: #ddd;
   float:right;
}
.login_submit{
  display:block;
  width:100%;
  height:42px;
  margin-top:30px;
  background :#1989fa;
  border-radius:4px;
  font-size:16px;
  line-height:42px;
  color:#fff;
  text-align:center;
  border:none;
}
.about{
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
}
</style>
